package LeetCode._02算法基础.day20其他;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 给你一个整数数组 nums ，设计算法来打乱一个没有重复元素的数组。
 * 打乱后，数组的所有排列应该是等可能的。
 * 实现 Solution class:
 *
 * Solution(int[] nums) 使用整数数组 nums 初始化对象
 * int[] reset() 重设数组到它的初始状态并返回
 * int[] shuffle() 返回数组随机打乱后的结果
 * @since 2022 - 09 - 16 - 9:04
 */
public class _384打乱数组 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        Solution solution = new Solution(nums);
        System.out.println(Arrays.toString(solution.shuffle()));
        System.out.println(Arrays.toString(solution.reset()));
        System.out.println(Arrays.toString(solution.shuffle()));
    }
}
class Solution {
    int[] nums;
    int[] original;
    public Solution(int[] nums) {
        this.nums = nums;
        original = new int[nums.length];
        System.arraycopy(nums, 0, original, 0, nums.length);
    }

    public int[] reset() {
        System.arraycopy(original, 0, nums, 0, original.length);
        return nums;
    }

    public int[] shuffle() {
        int[] shuffled = new int[nums.length];
        List<Integer> list = new ArrayList<>();
        for (int num : nums) list.add(num);

        Random random = new Random();
        for(int i = 0; i < nums.length; i++){
            int index = random.nextInt(list.size());
            shuffled[i] = list.remove(index);
        }
        System.arraycopy(shuffled, 0, nums, 0, shuffled.length);
        return nums;
    }
//    public int[] shuffle() {
//        Random random = new Random();
//        for(int i = 0; i < nums.length; i++){
//            int j = i + random.nextInt(nums.length - i);
//            int temp = nums[i];
//            nums[i] = nums[j];
//            nums[j] = temp;
//        }
//        return nums;
//    }
}